package com.flyqiu.form.core;

import com.flyqiu.common.tools.FlyQiuCollectionTools;
import com.flyqiu.form.api.FlyQiuForm;
import com.flyqiu.form.api.col.FlyQiuStoreColTypeManage;
import com.flyqiu.form.api.config.IFlyQiuFormConfig;
import com.flyqiu.form.api.event.FlyQiuTableDataEventManage;
import com.flyqiu.form.api.event.FlyQiuTableEventManage;
import com.flyqiu.form.api.service.FlyQiuTableConfigService;
import com.flyqiu.form.api.store.FlyQiuFormCoreService;
import com.flyqiu.form.api.store.FlyQiuFormStoreManage;
import com.flyqiu.form.common.exceptions.FlyQiuFormException;
import com.flyqiu.form.core.event.GlobalFlyQiuTableDataEvent;
import com.flyqiu.form.core.event.GlobalFlyQiuTableEvent;

public abstract class BaseFlyQiuForm implements FlyQiuForm {

    protected DefaultFlyQiuFormContext context;

    protected IFlyQiuFormConfig qiuFormConfig;

    public BaseFlyQiuForm() {

    }


    @Override
    public void init(IFlyQiuFormConfig config) {
        if (context == null) {
            throw new FlyQiuFormException("context is null");
        }
        this.qiuFormConfig = config;

        //加载表存储
        loadFormStores(context.getFormStoreManage());
        //注册列类型管理
        loadFlyQiuStoreColType(context.getStoreColTypeManage());

        registerConfigComponents();
    }

    private void registerConfigComponents() {
        FlyQiuTableEventManage formEventManage = context.getFormEventManage();
        formEventManage.register(new GlobalFlyQiuTableEvent(context));

        FlyQiuCollectionTools.iterator(qiuFormConfig.getFlyQiuTableEvents(), formEventManage::register);

        FlyQiuTableDataEventManage flyQiuTableDataEventManage = context.getFormDataEventManage();
        flyQiuTableDataEventManage.register(new GlobalFlyQiuTableDataEvent());
        FlyQiuCollectionTools.iterator(qiuFormConfig.getFlyQiuTableDataEvents(), flyQiuTableDataEventManage::register);


    }


    protected abstract void loadFlyQiuStoreColType(FlyQiuStoreColTypeManage flyQiuStoreColTypeManage);


    protected abstract void loadFormStores(FlyQiuFormStoreManage formStoreManage);


    @Override
    public FlyQiuFormCoreService getCoreFormService() {
        return context.getFlyQiuCoreFormService();
    }

    @Override
    public DefaultFlyQiuFormContext getContext() {
        return context;
    }

    @Override
    public FlyQiuTableConfigService getTableConfigService() {
        return context.getTableConfigService();
    }


}
